<template>
  <div>
    <!-- Hero Section with Lazy Loading -->
    <div class="relative w-full h-screen max-h-[800px] z-10">
      <div class="w-full h-full flex flex-col pt-[100px] items-center bg-gradient-to-b from-black/40 to-black/25 pt-16">
        <h1 class="text-white text-4xl md:text-5xl font-medium mt-24 md:mt-32 drop-shadow-lg text-center px-4">
          视频素材 , vvvfx更专业
        </h1>

        <p class="font-medium text-white/70 text-base md:text-lg mt-4 drop-shadow-lg text-center px-4">
          <span>vvvfx<span class="mx-2">12</span>年 , 已有 {{ formatNumber(97591) }} 名供稿人加入</span>
          <span class="hidden md:inline"> , </span>
          <span class="block md:inline mt-2 md:mt-0">本周上架 {{ formatNumber(76883) }} 件视频素材</span>
        </p>

        <!-- Search Section -->
        <div class="mt-8 w-full max-w-[800px] mx-4">
          <v-card rounded="lg" elevation="3" class="overflow-hidden">
            <v-tabs
              v-model="activeTab"
              bg-color="white"
              class="border-b"
            >
              <v-tab
                v-for="tab in searchTabs"
                :key="tab.id"
                :value="tab.id"
                @click="handleSearchByCategory(tab)"
                class="text-base py-4"
              >
                {{ tab.name }}
              </v-tab>
            </v-tabs>

            <v-card-text class="py-0">
              <div class="w-full flex relative">
                <input
                  v-model="searchQuery"
                  class="w-full outline-none px-6 text-black border-0 h-16 text-base pr-[124px] transition-colors focus:bg-gray-50"
                  :placeholder="getPlaceholder"
                  role="combobox"
                  aria-expanded="false"
                  autocomplete="off"
                  name="wd"
                  @keyup.enter="handleSearch"
                />
                <div class="absolute right-0 h-full flex items-center pr-4">
                  <v-btn
                    variant="text"
                    icon="mdi-magnify"
                    :loading="isLoading"
                    :disabled="!searchQuery.trim()"
                    @click="handleSearch"
                    class="transition-transform hover:scale-110"
                  />
                </div>
              </div>
            </v-card-text>
          </v-card>
        </div>

        <!-- Feature Bar -->
        <div class="absolute w-full bottom-0 flex justify-center h-20 md:h-24 bg-black/30 backdrop-blur-sm">
          <div class="w-full max-w-screen-xl grid grid-cols-2 md:grid-cols-4 gap-4 px-4 md:px-11 py-4">
            <div
              v-for="(feature, idx) in features"
              :key="idx"
              class="flex items-center space-x-3 md:space-x-5"
            >
              <img
                class="w-6 h-6 md:w-7 md:h-7"
                :src="getImgUrl(feature.icon)"
                :alt="feature.title"
                loading="lazy"
              />
              <div class="space-y-0.5">
                <label class="text-sm md:text-base font-medium text-[#f5f5f5]">{{ feature.title }}</label>
                <p class="text-xs md:text-sm text-white/70">{{ feature.desc }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Background Video with Preload -->
      <div class="absolute inset-0 z-[-1] overflow-hidden bg-black">
        <video
          class="w-full h-full object-cover"
          preload="metadata"
          playsinline
          autoplay
          muted
          loop
          poster="https://s1.vjshi.com/carousel/2023-11-06/acfd24a646f921ddafa318e8ca0e9fb1.jpg"
        >
          <source
            src="../assets/home/bgVideo.mp4"
            type="video/mp4"
          />
        </video>
      </div>
    </div>

    <!-- Category Grid -->
    <div class="w-full max-w-screen-xl px-4 md:px-11 mx-auto mt-12 md:mt-15">
      <div class="grid grid-cols-2 md:grid-cols-3 gap-4 md:gap-7">
        <div
          v-for="(item, index) in searchTabs"
          :key="index"
          @click="router.push('/categoryList?categoryId=' + item.id)"
          class="bg-[#f9f9f9] rounded-xl py-6 flex flex-col items-center space-y-3 hover:shadow-lg hover:bg-white transition-all duration-300 cursor-pointer"
        >
          <img
            class="w-6 h-6 md:w-7 md:h-7"
            :src="categories[item.name]"
            :alt="item.name"
            loading="lazy"
          />
          <h3 class="text-sm md:text-base text-neutral-700 font-medium">{{ item.name }}</h3>
        </div>
      </div>
    </div>

    <!-- Material Discovery -->
    <div class="pt-24 md:pt-36 w-full max-w-screen-xl px-4 md:px-11 mx-auto text-center">
      <h2 class="text-3xl md:text-4xl font-medium text-black">发现更多好素材</h2>

      <div class="mt-6 md:mt-8">
        <btn-tabs
          v-model:modelValue="activeCategory"
          :tabs="materialCategories"
          :disabled="isLoading"
          isAll
          @change="handleSearchByCategoryByEmits"
        />
      </div>

      <!-- Content Container with Fixed Height -->
      <div class="min-h-[400px] relative mt-8">
        <!-- Error State -->
        <v-alert
          v-if="error"
          type="error"
          variant="tonal"
          class="mx-auto max-w-md absolute left-1/2 transform -translate-x-1/2"
        >
          {{ error }}
          <template v-slot:append>
            <v-btn
              variant="text"
              @click="handleRetry"
              class="ml-2"
            >
              重试
            </v-btn>
          </template>
        </v-alert>

                  <!-- Loading State -->
        <div
          v-else-if="isLoading"
          class="absolute inset-0"
        >
          <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6">
            <v-card
              v-for="n in 8"
              :key="n"
              class="!bg-transparent"
              flat
            >
              <v-skeleton-loader
                type="card"
                class="!bg-transparent"
              >
                <template #image>
                  <v-skeleton-loader
                    type="image"
                    height="160"
                    class="rounded-t-lg"
                  />
                </template>
                <template #text>
                  <div class="px-3 pb-3 pt-2 space-y-3">
                    <v-skeleton-loader type="text" class="!h-5" />
                    <div class="flex gap-2">
                      <v-skeleton-loader type="chip" width="60" class="!h-4" />
                      <v-skeleton-loader type="chip" width="80" class="!h-4" />
                    </div>
                    <div class="flex justify-between items-center pt-1">
                      <v-skeleton-loader type="text" width="80" class="!h-4" />
                      <v-skeleton-loader type="text" width="60" class="!h-4" />
                    </div>
                  </div>
                </template>
              </v-skeleton-loader>
            </v-card>
          </div>
        </div>

        <!-- Content -->
        <template v-else>
          <v-fade-transition>
            <div class="relative">
              <card-list :list="hotData" />
            </div>
          </v-fade-transition>
        </template>
      </div>

      <!-- View More Button -->
      <div class="w-full flex justify-center py-16 md:py-20">
        <v-btn
          rounded="xl"
          size="x-large"
          elevation="0"
          @click="router.push(`/categoryList?categoryId=${activeTab}`)"
          class="bg-[#ededed] hover:bg-[#e0e0e0] transition-colors"
        >
          查看更多
        </v-btn>
      </div>
    </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { getMaterialCategory, getMaterialList } from '@/api/material'
import { useAppStore } from '@/stores/app'

// Router and Store
const router = useRouter()
const appStore = useAppStore()

// State Management
const activeTab = ref('0')
const activeCategory = ref('0')
const searchQuery = ref('')
const isLoading = ref(false)
const error = ref(null)
const hotData = ref([])
const searchTabs = ref([])

// Constants
const features = [
  { icon: 'home-banner-1-MG7TK2WJ.svg', title: '精准搜索', desc: '自研多模态搜索算法' },
  { icon: 'home-banner-2-EX3FXF5Z.svg', title: '正版授权', desc: '每件素材50万保障金' },
  { icon: 'home-banner-3-TS3DSPZV.svg', title: '海量更新', desc: '汇集全球优质供稿人' },
  { icon: 'home-banner-4-IQZKQC3O.svg', title: '安心售后', desc: '质量问题直接退' }
]

const categories = {
  "Houdini工程": getImgUrl('classification-5.svg'),
  "AE模版": getImgUrl('classification-2.svg'),
  "模型": getImgUrl('classification-3.svg')
}

// Computed Properties
const materialCategories = computed(() => {
  return searchTabs.value.find((item) => item.id === activeTab.value)?.second_categories || []
})

const getPlaceholder = computed(() => {
  const placeholders = {
    4: '输入关键词，找Houdini工程',
    5: '输入关键词，找AE模板',
    6: '输入关键词，找模型'
  }
  return placeholders[activeTab.value]
})

// Methods
function getImgUrl(path) {
  return new URL(`../assets/home/${path}`, import.meta.url).href
}

function formatNumber(num) {
  return new Intl.NumberFormat('zh-CN').format(num)
}

async function fetchMaterials(first_category_id, second_category_id) {
  try {
    isLoading.value = true
    const response = await getMaterialList({
      offset: 0,
      name: searchQuery.value || '',
      limit: 10,
      first_category_id,
      second_category_id: second_category_id !== '0' ? [second_category_id] : undefined
    })
    hotData.value = response.data
  } catch (err) {
    error.value = err.message
  } finally {
    isLoading.value = false
  }
}

function handleSearchByCategory(item) {
  appStore.activeMaterialCategory = item.id
  activeCategory.value="0"
  fetchMaterials(item.id, activeCategory.value)
}

function handleSearchByCategoryByEmits(item) {
  activeCategory.value = item.id
  fetchMaterials(activeTab.value, item.id)
}

function handleSearch() {
  if (!searchQuery.value.trim()) return
  router.push({
    path: '/categoryList',
    query: {
      q: searchQuery.value,
      categoryId: activeTab.value,
    }
  })
}

function handleRetry() {
  error.value = null
  fetchMaterials(activeTab.value, activeCategory.value)
}

// Lifecycle
onMounted(async () => {
  console.log('Home Page Mounted');

  searchTabs.value = appStore.materialCategory

  if (appStore.activeMaterialCategory) {
    activeTab.value = Number(appStore.activeMaterialCategory)
  } else {
    activeTab.value = searchTabs.value[0]?.id
    appStore.activeMaterialCategory = activeTab.value
  }

  await fetchMaterials(activeTab.value, activeCategory.value)
})
</script>

<style scoped>
:deep(.tooltip-padding) {
  padding: 0 !important;
}

/* Responsive transitions */
@media (max-width: 768px) {
  .v-enter-active,
  .v-leave-active {
    transition-duration: 0.2s;
  }
}
</style>
